from datetime import datetime
import markdown
from app import db

class Comment(db.Model):
    __tablename__ = 'comments'
    
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text)
    body_html = db.Column(db.Text)
    created = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    approved = db.Column(db.Boolean, default=False)
    
    # 外键
    author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))
    parent_id = db.Column(db.Integer, db.ForeignKey('comments.id'), nullable=True)
    
    # 关系
    replies = db.relationship('Comment', backref=db.backref('parent', remote_side=[id]),
                             lazy='dynamic', cascade='all, delete-orphan')
    
    def __init__(self, **kwargs):
        super(Comment, self).__init__(**kwargs)
        if self.body:
            self.on_body_changed()
    
    def on_body_changed(self):
        self.body_html = markdown.markdown(self.body, extensions=[
            'markdown.extensions.fenced_code',
            'markdown.extensions.codehilite',
            'mdx_math'
        ])
    
    def __repr__(self):
        return f'<Comment {self.id}>'